<template>
    <div>
        <NavHeader />
        <!-- 商品详请盒子 -->
        <div class="detail-box">
            <div class="left">
                <div class="actor">
                    <img
                        v-if="serviceDetail?.photos?.[index]?.url"
                        :src="servicePort + serviceDetail?.photos?.[index]?.url || ''"
                        alt="展示图"
                    />
                    <img v-else :src="servicePort + '/vehicle/default_img.png'" />
                </div>
                <ul class="shopimg">
                    <li
                        v-for="(item, index) in serviceDetail.photos"
                        :data-index="index"
                        :key="item.id"
                    >
                        <img :src="servicePort + item?.url || ''" alt="导航图" />
                    </li>
                </ul>
            </div>
            <div class="right">
                <h2>{{ serviceDetail?.shopName || '暂无信息' }}</h2>
                <!-- 价格信息 -->
                <div class="price">
                    <p>
                        <span class="text">价格：</span
                        ><span class="prePri">￥{{ (serviceDetail?.money + 20)?.toFixed(2) }}</span>
                    </p>
                    <p>
                        <span class="text">活动价：</span
                        ><span class="pri">￥{{ serviceDetail?.money?.toFixed(2) }}</span>
                    </p>
                </div>
                <div class="message">
                    <p>
                        <span class="text">省份：</span
                        ><span class="text1">{{ serviceDetail?.province || '暂无' }}</span>
                    </p>
                    <p>
                        <span class="text">市级:</span
                        ><span class="text1">{{ serviceDetail?.city || '暂无' }}</span>
                    </p>
                </div>
                <div class="message">
                    <p>
                        <span class="text">服务类型:</span>
                        <span class="text1">{{ serviceDetail?.category || '暂无' }}</span>
                    </p>
                    <p>
                        <span class="text">服务要点:</span>
                        <span class="text1">{{ serviceDetail?.service_point || '暂无' }}</span>
                    </p>
                    <p>
                        <span class="text">联系电话:</span>
                        <span class="text1">{{ serviceDetail?.shop?.phone || '暂无' }}</span>
                    </p>
                    <p>
                        <span class="text">服务描述:</span>
                        <span class="text1">
                            {{ serviceDetail?.description || '暂无' }}
                        </span>
                    </p>
                </div>
                <div class="opera">
                    <span class="buy" @click="addOrder"> 购买服务 </span>
                    <span class="car" @click="addCart">
                        <i class="iconfont icon-marketCar"></i>
                        加入购物车
                    </span>
                </div>
                <div class="serves">
                    <p>
                        <span v-for="item in servesTip" :key="item">{{ item }}</span>
                    </p>
                </div>
            </div>
        </div>

        <!-- 购买服务 区域 -->
        <el-dialog v-model="dialogVisible" title="✅ 确定购买服务" width="500">
            <div>
                <template v-if="carOptions.length === 0">
                    <span>尊敬的用户，您还没有绑定自己的车辆，是否前往绑定</span>
                </template>

                <template v-else-if="carOptions.length !== 0">
                    <div>
                        <p class="car_form_title" v-if="carOptions.length > 1">
                            尊敬的用户，系统检测到您有多辆车辆，请选择服务车辆
                        </p>
                        <p class="car_form_title" v-else>尊敬的用户，请选择服务车辆</p>
                        <div class="car_form">
                            <el-form
                                ref="carFormRef"
                                :model="carForm"
                                :rules="rules"
                                label-width="100px"
                            >
                                <el-form-item label="选择车辆" prop="carId">
                                    <el-select
                                        v-model="carForm.carId"
                                        placeholder="请选择车辆"
                                        style="width: 100%"
                                    >
                                        <el-option
                                            v-for="item in carOptions"
                                            :key="item.value"
                                            :label="item.label + ' ( ' + item.license_plate + ' ) '"
                                            :value="item.value"
                                        />
                                    </el-select>
                                </el-form-item>
                            </el-form>
                        </div>
                    </div>
                </template>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="cancel">取消</el-button>
                    <el-button type="primary" @click="onOk"> 确定 </el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 加入购物车 -->
        <el-dialog v-model="dialogVisibleCart" title="🛒 是否要加入购物车" width="500">
            <div>
                <template v-if="carOptions.length === 0">
                    <span>尊敬的用户，您还没有绑定自己的车辆，是否前往绑定</span>
                </template>

                <template v-else-if="carOptions.length !== 0">
                    <div>
                        <p class="car_form_title" v-if="carOptions.length > 1">
                            尊敬的用户，系统检测到您有多辆车辆，请选加入购物车的服务车辆
                        </p>
                        <p class="car_form_title" v-else>尊敬的用户，请选加入购物车的服务车辆</p>
                        <div class="car_form">
                            <el-form
                                ref="cartFormRef"
                                :model="cartForm"
                                :rules="rulesCart"
                                label-width="100px"
                            >
                                <el-form-item label="选择车辆" prop="carId">
                                    <el-select
                                        v-model="cartForm.carId"
                                        placeholder="请选择车辆"
                                        style="width: 100%"
                                    >
                                        <el-option
                                            v-for="item in carOptions"
                                            :key="item.value"
                                            :label="item.label + ' ( ' + item.license_plate + ' ) '"
                                            :value="item.value"
                                        />
                                    </el-select>
                                </el-form-item>
                            </el-form>
                        </div>
                    </div>
                </template>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="cancel">取消</el-button>
                    <el-button type="primary" @click="onOkCart"> 确定 </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { onMounted, ref, nextTick, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getServiceDetailById, addCartToUser } from '@/api/home'
import { getCarByUserId, addOrderService } from '@/api/service'
import { servicePort } from '@/request'
import { useNavList, useUserInfo } from '../../store/index'
import message from '@/utils/message'

const { servesTip } = useNavList()
const { userInfo } = useUserInfo()
const router = useRouter()

const carFormRef = ref(null)
const cartFormRef = ref(null)
const serviceDetail = reactive({})
const dialogVisible = ref(false)
const dialogVisibleCart = ref(false)
const carForm = reactive({
    carId: ''
})
const cartForm = reactive({
    carId: ''
})
const carOptions = reactive([])

const {
    params: { id }
} = useRoute()

const rules = {
    carId: [{ required: true, message: '请选择一个车辆', trigger: 'blur' }]
}

const rulesCart = {
    carId: [{ required: true, message: '请选择一个车辆', trigger: 'blur' }]
}
const cancel = () => {
    dialogVisible.value = false
    dialogVisibleCart.value = false
    cartFormRef.value.resetFields()
    carFormRef.value.resetFields()
}

const onOk = async () => {
    await carFormRef.value.validate(async (valid, fields) => {
        if (!valid) return
        // 检验成功后的逻辑

        const orderData = {
            serviceId: serviceDetail.id,
            carId: carForm.carId
        }

        const res = await addOrderService(orderData)
        if (res.status !== 200 || res.data.code === 900) return message.error(res.data.message)
        if (res.data.code === 901) return message.error('您的账户余额不足请先充值')

        message.success('购买成功')
        dialogVisible.value = false
        setTimeout(() => {
            router.push('/order')
        }, 1000)
    })
}

const onOkCart = async () => {
    await cartFormRef.value.validate(async (valid, fields) => {
        if (!valid) return
        // 检验成功后的逻辑
        const cartData = {
            serviceId: serviceDetail.id,
            carId: cartForm.carId
        }

        const res = await addCartToUser(cartData)
        if (res.status !== 200 || res.data.code === 900) return message.error(res.data.message)

        message.success('加入购物车成功')
        dialogVisible.value = false
        setTimeout(() => {
            router.push('/cart')
        }, 1000)
    })
}

const getDetailById = async () => {
    const res = await getServiceDetailById(id)
    if (res.status !== 200) return message.error('获取数据失败')
    Object.assign(serviceDetail, res.data)
}

getDetailById()

// 图片展示索引值
let index = ref(0)
onMounted(() => {
    // 获取到父元素
    let ul = document.querySelector('.shopimg')
    ul.addEventListener('mouseover', (e) => {
        let curIndex
        if (e.target.nodeName === 'LI') {
            curIndex = parseInt(e.target.dataset.index)
            index.value = curIndex
        }
        if (e.target.nodeName === 'IMG') {
            curIndex = parseInt(e.target.parentNode.dataset.index)
            index.value = curIndex
        }
    })
})

// 加入购物车
const addCart = async () => {
    dialogVisibleCart.value = true
    const res = await getCarByUserId()
    if (res.status !== 200) return
    const options = res.data.map((item) => {
        return {
            value: item.id,
            label: item.brand,
            license_plate: item.license_plate
        }
    })
    Object.assign(carOptions, options)
}

// 立即购买
const addOrder = async () => {
    const res = await getCarByUserId()
    if (res.status !== 200) return

    dialogVisible.value = true

    const options = res.data.map((item) => {
        return {
            value: item.id,
            label: item.brand,
            license_plate: item.license_plate
        }
    })
    Object.assign(carOptions, options)
}
</script>

<style lang="scss" scoped>
.detail-box {
    width: 1120px;
    margin: 0 auto;
    height: 500px;

    .left {
        padding-top: 50px;
        width: 50%;
        float: left;

        .actor {
            width: 100%;
            text-align: center;
            position: relative;

            img {
                width: 430px;
                height: 430px;
            }
        }

        .shopimg {
            margin-top: 15px;
            margin-left: auto;
            margin-right: auto;
            width: 430px;

            li {
                display: inline-block;
                width: 20%;
                height: 67px;
                cursor: pointer;

                img {
                    height: 62px;
                    width: 62px;

                    &:hover {
                        border: 2px solid #f5f5f5;
                    }
                }
            }
        }
    }

    .right {
        width: 50%;
        padding-top: 50px;
        float: right;
        font-size: 12px;
        color: #999;

        .price {
            padding: 5px 12px;
            margin-top: 18px;
            margin-right: 80px;
            background-color: #e9e9e9;
            background-image: url('../../assets/pricebg.png');
            background-repeat: no-repeat;
            background-size: cover;

            p {
                line-height: 24px;
                margin-bottom: 5px;

                .text {
                    display: inline-block;
                    width: 75px;
                }

                .prePri {
                    text-decoration: line-through;
                    font-size: 14px;
                    color: #333;
                }

                .pri {
                    font-weight: 600;
                    font-size: 24px;
                    color: #ff0036;
                }
            }
        }

        .message {
            padding: 5px 12px;
            margin-top: 18px;

            p {
                line-height: 24px;

                .text {
                    display: inline-block;
                    width: 75px;
                }

                .text1 {
                    font-size: 16px;
                    color: #000000;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    overflow: hidden;
                }
            }
        }

        .purchase {
            padding: 5px 12px;
            margin-top: 18px;

            .ipt {
                width: 120px;
                padding-left: 10px;
                line-height: 32px;
                outline: none;
                border: 1px solid #ccc;
            }
        }

        .opera {
            padding: 5px 12px;
            margin-top: 18px;
            font-size: 14px;

            .buy {
                width: 200px;
                display: inline-block;
                cursor: pointer;
                line-height: 38px;
                text-align: center;
                color: #95bf47;
                border: 1px solid #95bf47;
                background-color: rgba(149, 191, 103, 0.1);
                margin-right: 5px;
            }

            .car {
                width: 200px;
                display: inline-block;
                cursor: pointer;
                line-height: 36px;
                text-align: center;
                border: 1px solid #95bf47;
                color: #fff;
                background-color: #95bf47;
            }
        }

        .serves {
            padding: 5px 12px;
            margin-top: 18px;

            p {
                line-height: 24px;

                span {
                    display: inline-block;
                    min-width: 75px;
                    color: #999;
                    font-size: 12px;
                }
            }
        }
    }
}
.car_form_title {
    margin-left: 10px;
    margin-top: 20px;
}
.car_form {
    margin-top: 30px;
}
</style>
